package xyz.yuzegod.megawalls.listener;

import net.citizensnpcs.api.CitizensAPI;
import org.bukkit.*;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.block.Chest;
import org.bukkit.craftbukkit.v1_8_R3.entity.CraftPlayer;
import org.bukkit.entity.Entity;
import org.bukkit.entity.ExperienceOrb;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.block.Action;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.FoodLevelChangeEvent;
import org.bukkit.event.entity.PlayerDeathEvent;
import org.bukkit.event.inventory.CraftItemEvent;
import org.bukkit.event.player.*;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.Plugin;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import xyz.yuzegod.megawalls.LPRankProvider;
import xyz.yuzegod.megawalls.MegaWalls;
import xyz.yuzegod.megawalls.classes.Classes;
import xyz.yuzegod.megawalls.classes.ClassesManager;
import xyz.yuzegod.megawalls.classes.ClassesSkin;
import xyz.yuzegod.megawalls.classes.mythic.mole.Mole;
import xyz.yuzegod.megawalls.game.FakePlayer;
import xyz.yuzegod.megawalls.game.Game;
import xyz.yuzegod.megawalls.game.GamePlayer;
import xyz.yuzegod.megawalls.game.GameTeam;
import xyz.yuzegod.megawalls.inventory.InventoryManager;
import xyz.yuzegod.megawalls.spectator.SpectatorSettings;
import xyz.yuzegod.megawalls.stats.CurrencyPackage;
import xyz.yuzegod.megawalls.stats.EffectStatsContainer;
import xyz.yuzegod.megawalls.stats.KitStatsContainer;
import xyz.yuzegod.megawalls.util.ItemBuilder;
import xyz.yuzegod.megawalls.util.ItemUtils;
import xyz.yuzegod.megawalls.util.PlayerUtils;

import java.util.ArrayList;
import java.util.List;

public class PlayerListener extends BaseListener
{
    private final Game game;
    private List<Material> craft;
    static int spawnProtection=MegaWalls.getInstance().getConfig().getInt("spawnprotection",10);
    
    public PlayerListener(final MegaWalls plugin) {
        super(plugin);
        this.craft = new ArrayList<Material>();
        this.game = plugin.getGame();
        this.craft.add(Material.FISHING_ROD);
        this.craft.add(Material.BUCKET);
        this.craft.add(Material.MINECART);
    }
    
    @EventHandler(priority = EventPriority.HIGHEST)
    public void onPlayerAdvancementAwarded(final PlayerAchievementAwardedEvent e) {
        e.setCancelled(true);
    }
    
    @EventHandler(priority = EventPriority.HIGHEST)
    public void onPlayerLogin(final PlayerLoginEvent e) {
        if (this.game == null && !e.getPlayer().isOp()) {
            e.setResult(PlayerLoginEvent.Result.KICK_OTHER);
            e.setKickMessage("§c未发现游戏实例,不能进入该服务器！");
            return;
        }
        if (this.game != null && Bukkit.getOnlinePlayers().size() >= this.game.getMaxPlayers()) {
            e.setResult(PlayerLoginEvent.Result.KICK_FULL);
            e.setKickMessage("§c该房间人数已满！");
        }
    }
    
    @EventHandler(priority = EventPriority.HIGHEST)
    public void onPlayerJoin(final PlayerJoinEvent e) {
        e.setJoinMessage((String)null);
        final Player player = e.getPlayer();
        final GamePlayer gamePlayer = GamePlayer.create(player.getUniqueId());
        gamePlayer.getPlayerStats().update();
        Bukkit.getScheduler().runTaskLaterAsynchronously((Plugin)MegaWalls.getInstance(), (Runnable)new Runnable() {
            @Override
            public void run() {
                final ClassesSkin defaultSkin = gamePlayer.getPlayerStats().getSelected().getDefaultSkin();
                PlayerUtils.skinChangeNoKill((CraftPlayer)player, defaultSkin.getValue(), defaultSkin.getSignature());
            }
        }, 1L);
        if (this.game.isWaiting()) {
            e.setJoinMessage(LPRankProvider.getPrefixColor(player.getPlayer()) + player.getDisplayName() + "§e加入了游戏(§b" + MegaWalls.getIngame().size() + "§e/§b" + this.game.getMaxPlayers() + "§e)！");
            if (this.game.getLobbyLocation() != null) {
                e.getPlayer().teleport(this.game.getLobbyLocation());
            }
            player.setGameMode(GameMode.ADVENTURE);
            player.getInventory().clear();
            player.getInventory().setArmorContents((ItemStack[])null);
            player.getActivePotionEffects().clear();
            player.setMaxHealth(20.0);
            player.setHealth(20.0);
            player.setFoodLevel(20);
            player.setFireTicks(0);
            player.setLevel(0);
            player.setExp(0.0f);
            player.getInventory().setItem(0, new ItemBuilder(Material.IRON_SWORD).setDisplayName("§a职业选择器§7(右键点击)").build());
            if (player.hasPermission("MegaWalls.forcestart")) {
                player.getInventory().setItem(7, new ItemBuilder(Material.DIAMOND).setDisplayName("§a开始游戏§7(右键点击)").build());
            }
            player.getInventory().setItem(1, new ItemBuilder(Material.EMERALD).setDisplayName("§a商店§7(右键点击)").build());
            player.getInventory().setItem(4, new ItemBuilder(Material.PAPER).setDisplayName("§e任务§7(右键点击)").build());
            player.getInventory().setItem(8, new ItemBuilder(Material.BED).setDisplayName("§c§l返回大厅§7(右键点击)").build());
        }
        else if (this.game.isStarted()) {
            if (gamePlayer.isSpectator() || gamePlayer.getGameTeam() == null || (FakePlayer.fakePlayerMap.containsKey(gamePlayer) && FakePlayer.fakePlayerMap.get(gamePlayer).isKilled())) {
                gamePlayer.toSpectator(null, null);
                if (this.game.getLobbyLocation() != null) {
                    e.getPlayer().teleport(this.game.getLobbyLocation());
                }
                Bukkit.getScheduler().runTaskLater((Plugin)MegaWalls.getInstance(), (Runnable)new Runnable() {
                    @Override
                    public void run() {
                        PlayerListener.this.game.registerScoreboardTeams();
                    }
                }, 30L);
                if (FakePlayer.list.contains(gamePlayer)) {
                    FakePlayer.list.remove(gamePlayer);
                    MegaWalls.updateRejoin(gamePlayer, "none", System.currentTimeMillis());
                }
                return;
            }
            if (FakePlayer.fakePlayerMap.containsKey(gamePlayer) && !FakePlayer.fakePlayerMap.get(gamePlayer).isKilled()) {
                GamePlayer.getOnlinePlayers().forEach(viewer -> viewer.sendMessage(gamePlayer.getDisplayName(viewer) + " §7重新连接"));
                player.teleport(FakePlayer.fakePlayerMap.get(gamePlayer).getLocation().clone());
                FakePlayer.fakePlayerMap.get(gamePlayer).delete();
                Bukkit.getScheduler().runTaskLater((Plugin)MegaWalls.getInstance(), (Runnable)new Runnable() {
                    @Override
                    public void run() {
                        PlayerListener.this.game.registerScoreboardTeams();
                    }
                }, 30L);
                if (FakePlayer.list.contains(gamePlayer)) {
                    FakePlayer.list.remove(gamePlayer);
                    MegaWalls.updateRejoin(gamePlayer, "none", System.currentTimeMillis());
                }
            }
        }
    }
    
    @EventHandler(priority = EventPriority.HIGHEST)
    public void onPlayerQuit(final PlayerQuitEvent e) {
        e.setQuitMessage((String)null);
        if (this.game.isWaiting()) {
            final GamePlayer gamePlayer = GamePlayer.get(e.getPlayer().getUniqueId());
            if (this.game.getPlayerParty(gamePlayer) != null) {
                this.game.getPlayerParty(gamePlayer).removePlayer(gamePlayer);
            }
            e.setQuitMessage(LPRankProvider.getPrefixColor(e.getPlayer()) + e.getPlayer().getDisplayName() + "§e已退出！");
            GamePlayer.remove(e.getPlayer().getUniqueId());
        }
        else if (this.game.isStarted() && !GamePlayer.get(e.getPlayer().getUniqueId()).isSpectator()) {
            final GamePlayer gamePlayer = GamePlayer.get(e.getPlayer().getUniqueId());
            new FakePlayer(gamePlayer);
        }
    }
    
    @EventHandler(priority = EventPriority.HIGHEST)
    public void onPlayerKick(final PlayerKickEvent e) {
        e.setLeaveMessage((String)null);
    }
    
    @EventHandler(priority = EventPriority.HIGHEST)
    public void onPlayerDeath(final PlayerDeathEvent e) {
        final Player player = e.getEntity();
        final GamePlayer gamePlayer = GamePlayer.get(player.getUniqueId());
        if (this.game.isWaiting() || gamePlayer.isSpectator()) {
            e.setDeathMessage((String)null);
            e.setKeepInventory(true);
            e.setKeepLevel(true);
            if (gamePlayer.isSpectator()) {
                PlayerUtils.respawn(player);
            }
            return;
        }
        e.setDeathMessage((String)null);
        e.setKeepInventory(false);
        e.setKeepLevel(false);
        PlayerUtils.respawn(player);
        final GameTeam playerTeam = gamePlayer.getGameTeam();
        if (player.getKiller() != null) {
            GamePlayer.get(player.getKiller().getUniqueId()).handleKill(gamePlayer, (Entity)e.getEntity());
        }
        else if (gamePlayer.getGameTeam().isWitherDead()) {
            for (final GamePlayer assistor : gamePlayer.getAssistsMap().getAssists(System.currentTimeMillis())) {
                assistor.getPlayerStats().giveCoins(new CurrencyPackage(15, "§b§l最终击杀 §c§l助攻"));
                if (this.game.isProtected(e.getEntity().getLocation())) {
                    assistor.getPlayerStats().giveCoins(new CurrencyPackage(9, "(防守奖励)"));
                }
                assistor.addFinalKills();
                final KitStatsContainer kitStats2 = assistor.getPlayerStats().getKitStats(assistor.getPlayerStats().getSelected());
                kitStats2.giveMasterPoints(1);
                kitStats2.addFinalAssists(1);
            }
            gamePlayer.getPlayerStats().addGames();
            final KitStatsContainer kitStats3 = gamePlayer.getPlayerStats().getKitStats(gamePlayer.getPlayerStats().getSelected());
            kitStats3.addGames();
            kitStats3.addPlayTime(MegaWalls.getInstance().getGame().getStartTime() - System.currentTimeMillis());
        }
        else {
            for (final GamePlayer assistor : gamePlayer.getAssistsMap().getAssists(System.currentTimeMillis())) {
                assistor.getPlayerStats().giveCoins(new CurrencyPackage(4, "§c§l助攻 §6击杀" + gamePlayer.getDisplayName(assistor)));
                if (this.game.isProtected(e.getEntity().getLocation())) {
                    assistor.getPlayerStats().giveCoins(new CurrencyPackage(9, "(防守奖励)"));
                }
                assistor.addKills();
            }
        }
        if (playerTeam.isWitherDead()) {
            gamePlayer.toSpectator("§c§l你死了！", "§7你现在是一名旁观者");
        }
        else {
            gamePlayer.setProtect(true);
            Bukkit.getScheduler().runTaskLater((Plugin)MegaWalls.getInstance(), (Runnable)new Runnable() {
                @Override
                public void run() {
                    player.teleport(playerTeam.getSpawnLocation());
                    ClassesManager.giveItems(gamePlayer);
                    player.sendMessage("§a因为我方凋零存活,§l你重生了");
                    player.addPotionEffect(new PotionEffect(PotionEffectType.INCREASE_DAMAGE,6*20,2));
                }
            }, 2L);
            Bukkit.getScheduler().runTaskLater((Plugin)MegaWalls.getInstance(), (Runnable)new Runnable() {
                @Override
                public void run() {
                    player.sendMessage("§c你的重生保护效果已消失！");
                    gamePlayer.setProtect(false);
                }
            }, 200L);
        }
        if (playerTeam.isDead()) {
            for (GamePlayer viewer:GamePlayer.getOnlinePlayers()) {
                EffectStatsContainer effectStats;
                GameTeam gameTeam = viewer.getGameTeam();
                effectStats = viewer.getPlayerStats().getEffectStats();
                viewer.getPlayer().sendMessage(effectStats.getColor(gameTeam.getTeamColor()).getChatColor() + gameTeam.getTeamColor().getText() + "队§e§l已被团灭！");
                viewer.sendTitle(effectStats.getColor(gameTeam.getTeamColor()).getChatColor() + gameTeam.getTeamColor().getText() + "队", "§f被淘汰了", 5, 40, 5);
            }
        }
    }
    
    @EventHandler(priority = EventPriority.HIGHEST)
    public void onPlayerMove(final PlayerMoveEvent e) {
        if (this.game.isStarted() && this.game.getCenterArea().isInRegion(e.getTo()) && !this.game.isWallsFall()) {
            e.setCancelled(true);
            e.getPlayer().teleport(e.getFrom());
            e.getPlayer().sendMessage("§c§l你不可以往这个方向前进！");
        }
    }
    
    @EventHandler(priority = EventPriority.HIGHEST)
    public void onAsyncPlayerChat(final AsyncPlayerChatEvent e) {
        final GamePlayer gamePlayer = GamePlayer.get(e.getPlayer().getUniqueId());
        if (this.game.isStarted()) {
            final String message = e.getMessage();
            if (gamePlayer.isSpectator()) {
                e.setFormat("§7[旁观者]" + ((gamePlayer.getGameTeam() != null) ? (" " + gamePlayer.getGameTeam().getTeamColor().getChatPrefix()) : "") + " " + LPRankProvider.getPrefix(gamePlayer.getPlayer()) + gamePlayer.getPlayer().getDisplayName() + LPRankProvider.getSuffix(gamePlayer.getPlayer()) + "§f: " + e.getMessage());
                e.getRecipients().removeIf(recipient -> !GamePlayer.get(recipient.getUniqueId()).isSpectator());
            }
            else if (message.startsWith("!")) {
                e.setMessage(message.replace("!", ""));
                e.setFormat("§6[喊话] " + gamePlayer.getGameTeam().getTeamColor().getChatPrefix() + " " + LPRankProvider.getPrefix(gamePlayer.getPlayer()) + gamePlayer.getPlayer().getName() + LPRankProvider.getSuffix(gamePlayer.getPlayer()) + "§f： " + e.getMessage());
            }
            else {
                final GameTeam team = gamePlayer.getGameTeam();
                String msg=e.getMessage().replaceAll("%","%%");
                e.setFormat(team.getTeamColor().getChatPrefix() + " " + LPRankProvider.getPrefix(gamePlayer.getPlayer()) + gamePlayer.getPlayer().getDisplayName() + LPRankProvider.getSuffix(gamePlayer.getPlayer()) + "§f： " + msg);
                e.getRecipients().removeIf(recipient2 -> !team.isInTeam(GamePlayer.get(recipient2.getUniqueId())));
            }
        }
        else {
            e.setFormat(LPRankProvider.getPrefix(gamePlayer.getPlayer()) + gamePlayer.getPlayer().getDisplayName() + LPRankProvider.getSuffix(gamePlayer.getPlayer()) + "§f： " + e.getMessage());
        }
    }
    
    @EventHandler(priority = EventPriority.HIGHEST)
    public void onCraftItem(final CraftItemEvent e) {
        if (this.craft.contains(e.getRecipe().getResult().getType())) {
            e.setCancelled(true);
        }
    }
    
    @EventHandler(priority = EventPriority.HIGHEST)
    public void onPlayerDropItem(final PlayerDropItemEvent e) {
        final GamePlayer gamePlayer = GamePlayer.get(e.getPlayer().getUniqueId());
        if (gamePlayer.isSpectator() || !this.game.isStarted()) {
            e.setCancelled(true);
            return;
        }
        final Player player = e.getPlayer();
        final ItemStack itemStack = e.getItemDrop().getItemStack();
        if (ClassesManager.isClassesItem(itemStack)) {
            e.setCancelled(true);
            player.sendMessage("§c无法将职业套装物品移出物品栏！");
        }
    }
    
    @EventHandler(priority = EventPriority.HIGHEST)
    public void onPlayerPickupItem(final PlayerPickupItemEvent e) {
        final GamePlayer gamePlayer = GamePlayer.get(e.getPlayer().getUniqueId());
        if (gamePlayer.isSpectator() || !this.game.isStarted()) {
            e.setCancelled(true);
            return;
        }
        if (e.getItem() instanceof ExperienceOrb || e.getItem().hasMetadata("Arrow")) {
            e.setCancelled(true);
            e.getItem().remove();
            return;
        }
        final ItemStack itemStack = e.getItem().getItemStack();
        if (ClassesManager.isClassesItem(itemStack)) {
            e.setCancelled(true);
            e.getItem().remove();
        }
    }
    
    @EventHandler(priority = EventPriority.HIGHEST)
    public void onPlayerExpChange(final PlayerExpChangeEvent e) {
        final GamePlayer gamePlayer = GamePlayer.get(e.getPlayer().getUniqueId());
        if (gamePlayer.isSpectator() || this.game.isStarted()) {
            e.setAmount(0);
        }
    }
    
    @EventHandler(priority = EventPriority.HIGHEST)
    public void onPlayerItemConsume(final PlayerItemConsumeEvent e) {
        if (e.getItem().getType() == Material.POTION) {
            Bukkit.getScheduler().runTaskLater((Plugin)MegaWalls.getInstance(), (Runnable)new Runnable() {
                @Override
                public void run() {
                    e.getPlayer().getInventory().remove(Material.GLASS_BOTTLE);
                }
            }, 1L);
        }
    }
    
    @EventHandler(priority = EventPriority.HIGHEST)
    public void onPlayerInteract(final PlayerInteractEvent e) {
        final Player player = e.getPlayer();
        final GamePlayer gamePlayer = GamePlayer.get(player.getUniqueId());
        if (e.getAction() == Action.LEFT_CLICK_AIR || e.getAction() == Action.LEFT_CLICK_BLOCK || e.getAction() == Action.RIGHT_CLICK_AIR || e.getAction() == Action.RIGHT_CLICK_BLOCK) {
            if (gamePlayer.isSpectator()) {
                e.setCancelled(true);
                final ItemStack item = player.getItemInHand();
                if (item == null || item.getType() == Material.AIR) {
                    return;
                }
                if (item.getType() == Material.BED) {
                    MegaWalls.getInstance().tpToLobby(player);
                    return;
                }
                if (item.getType() == Material.COMPASS) {
                    if (e.getAction() == Action.RIGHT_CLICK_AIR || e.getAction() == Action.RIGHT_CLICK_BLOCK) {
                        this.game.openSpectatorInventory(gamePlayer);
                        return;
                    }
                    if ((e.getAction() == Action.LEFT_CLICK_AIR || e.getAction() == Action.LEFT_CLICK_BLOCK) && gamePlayer.getSpectatorTarget() != null) {
                        gamePlayer.getSpectatorTarget().tp();
                        return;
                    }
                }
                else if (item.getType() == Material.DIODE) {
                    InventoryManager.SPECTATORSETTINGS.open(player);
                    return;
                }
            }
            else if (this.game.isWaiting()) {
                final ItemStack item = player.getItemInHand();
                if (item == null || item.getType() == Material.AIR) {
                    return;
                }
                if (e.getItem().getType() == Material.IRON_SWORD) {
                    e.setCancelled(true);
                    InventoryManager.CLASSESSELECTOR.open(player);
                    return;
                }
                if (e.getItem().getType() == Material.DIAMOND && player.hasPermission("MegaWalls.forcestart")) {
                    e.setCancelled(true);
                    this.game.forceStart();
                    return;
                }
                if (e.getItem().getType() == Material.EMERALD) {
                    e.setCancelled(true);
                    InventoryManager.SHOPMENU.open(player);
                    return;
                }
                if (e.getItem().getType() == Material.PAPER) {
                    e.setCancelled(true);
                    InventoryManager.TASKMENU.open(player);
                    return;
                }
                if (item.getType() == Material.BED) {
                    e.setCancelled(true);
                    MegaWalls.getInstance().tpToLobby(player);
                    return;
                }
            }
            else if (this.game.isStarted()) {
                if (!this.game.isWallsFall() && e.getAction() == Action.RIGHT_CLICK_BLOCK && e.getClickedBlock() != null && (e.getClickedBlock().getType() == Material.TRAPPED_CHEST || e.getClickedBlock().getType() == Material.FURNACE || e.getClickedBlock().getType() == Material.BURNING_FURNACE)) {
                    final Block block = e.getClickedBlock();
                    if (this.game.getPlayerParty(gamePlayer) != null && this.game.getPlayerParty(gamePlayer).isProtectedBlock(block)) {
                        if (block.getType() == Material.TRAPPED_CHEST && block.getRelative(BlockFace.UP).getType() != null && block.getRelative(BlockFace.UP).getType() != Material.AIR) {
                            player.openInventory(((Chest)block.getState()).getBlockInventory());
                        }
                        return;
                    }
                    else {
                        if (!gamePlayer.isProtectedBlock(block)) {
                            e.setCancelled(true);
                            gamePlayer.sendMessage("§c你不能使用这个" + ((block.getType() == Material.TRAPPED_CHEST) ? "陷阱箱" : "熔炉") + "！");
                            return;
                        }
                        if (block.getType() == Material.TRAPPED_CHEST && block.getRelative(BlockFace.UP).getType() != null && block.getRelative(BlockFace.UP).getType() != Material.AIR) {
                            player.openInventory(((Chest)block.getState()).getBlockInventory());
                            return;
                        }
                    }
                }
                final ItemStack item = player.getItemInHand();
                if (item == null || item.getType() == Material.AIR) {
                    return;
                }
                if (e.getItem().getType() == Material.ENDER_CHEST) {
                    e.setCancelled(true);
                    player.openInventory(gamePlayer.getEnderChest());
                    gamePlayer.playSound(Sound.CHEST_OPEN, 2.0f, 1.0f);
                    return;
                }
                if (((e.getAction() == Action.RIGHT_CLICK_BLOCK || e.getAction() == Action.RIGHT_CLICK_AIR) && ItemUtils.isSword(item)) || ((e.getAction() == Action.LEFT_CLICK_BLOCK || e.getAction() == Action.LEFT_CLICK_AIR) && e.getItem().getType() == Material.BOW && !(ClassesManager.getSelected(gamePlayer) instanceof Mole))) {
                    if (gamePlayer.getEnergy() == 100) {
                        final Classes classes = ClassesManager.getSelected(gamePlayer);
                        if (classes.getMainSkill().use(gamePlayer, gamePlayer.getPlayerStats().getKitStats(classes))) {
                            e.setCancelled(true);
                            gamePlayer.setEnergy(0);
                            gamePlayer.sendActionBar(classes.getSkillTip(gamePlayer));
                            gamePlayer.sendMessage("§a你的" + classes.getMainSkill().getName() + "技能已激活！");
                            if (gamePlayer.getPlayerStats().getKitStats(classes).getLevel() >= 3) {
                                ClassesManager.playSkillEffect(player);
                            }
                        }
                    }
                }
                else if ((e.getAction() == Action.RIGHT_CLICK_BLOCK || e.getAction() == Action.RIGHT_CLICK_AIR) && ItemUtils.isSpade(item) && ClassesManager.getSelected(gamePlayer) instanceof Mole) {
                    if (gamePlayer.getEnergy() == 100) {
                        final Classes classes = ClassesManager.getSelected(gamePlayer);
                        if (classes.getMainSkill().use(gamePlayer, gamePlayer.getPlayerStats().getKitStats(classes))) {
                            e.setCancelled(true);
                            gamePlayer.setEnergy(0);
                            gamePlayer.sendActionBar(classes.getSkillTip(gamePlayer));
                            gamePlayer.sendMessage("§a你的" + classes.getMainSkill().getName() + "技能已激活！");
                            if (gamePlayer.getPlayerStats().getKitStats(classes).getLevel() >= 3) {
                                ClassesManager.playSkillEffect(player);
                            }
                        }
                    }
                }
                else if (e.getItem().getType() == Material.COMPASS) {
                    if (e.getAction() == Action.RIGHT_CLICK_BLOCK || e.getAction() == Action.RIGHT_CLICK_AIR) {
                        e.setCancelled(true);
                        gamePlayer.getPlayerCompass().next();
                        return;
                    }
                    if (e.getAction() == Action.LEFT_CLICK_BLOCK || e.getAction() == Action.LEFT_CLICK_AIR) {
                        e.setCancelled(true);
                        gamePlayer.getPlayerCompass().previous();
                        return;
                    }
                }
            }
        }
        if (gamePlayer.isSpectator()) {
            e.setCancelled(true);
        }
    }
    @EventHandler
    public void onInstaFurnace(PlayerInteractEvent e){
        if (game.isStarted()&&!game.isWallsFall()&& e.getClickedBlock() != null){
            final Player player = e.getPlayer();
            final GamePlayer gamePlayer = GamePlayer.get(player.getUniqueId());
            if (gamePlayer.isSpectator()){
                return;
            }
            if (player.isSneaking()){
                return;
            }
            if (e.getClickedBlock().getType()==Material.FURNACE){
                if (player.getItemInHand().getType()==Material.IRON_ORE){
                    e.setCancelled(true);
                    int amount=player.getItemInHand().getAmount();
                    player.setItemInHand(new ItemStack(Material.IRON_INGOT,amount));
                }
            }
        }
    }
    
    @EventHandler(priority = EventPriority.HIGHEST)
    public void onFoodLevelChange(final FoodLevelChangeEvent e) {
        if (e.getEntity() instanceof Player && (GamePlayer.get(e.getEntity().getUniqueId()).isSpectator() || !this.game.isStarted())) {
            e.setCancelled(true);
        }
    }
    
    @EventHandler(priority = EventPriority.HIGHEST)
    public void onPlayerGameModeChange(final PlayerGameModeChangeEvent e) {
        if (GamePlayer.get(e.getPlayer().getUniqueId()).isSpectator()) {
            e.getPlayer().setAllowFlight(true);
        }
    }
    
    @EventHandler(priority = EventPriority.HIGHEST)
    public void onPlayerInteractEntity(final PlayerInteractEntityEvent e) {
        if (GamePlayer.get(e.getPlayer().getUniqueId()).isSpectator() || !this.game.isStarted()) {
            e.setCancelled(true);
        }
    }
    
    @EventHandler(priority = EventPriority.HIGHEST)
    public void onPlayerInteractAtEntity(final PlayerInteractAtEntityEvent e) {
        final GamePlayer gamePlayer = GamePlayer.get(e.getPlayer().getUniqueId());
        if (!gamePlayer.isSpectator() && this.game.isStarted()) {
            return;
        }
        if (CitizensAPI.getNPCRegistry().isNPC(e.getRightClicked())) {
            return;
        }
        if (!gamePlayer.isSpectator() || !this.game.isStarted() || !(e.getRightClicked() instanceof Player) || !SpectatorSettings.get(gamePlayer).getOption(SpectatorSettings.Option.FIRSTPERSON)) {
            e.setCancelled(true);
            return;
        }
        e.setCancelled(true);
        if (GamePlayer.get(e.getRightClicked().getUniqueId()).isSpectator()) {
            return;
        }
        gamePlayer.sendTitle("§a正在旁观§7" + e.getRightClicked().getName(), "§a点击左键打开菜单  §c按Shift键退出", 0, 20, 0);
        e.getPlayer().setGameMode(GameMode.SPECTATOR);
        e.getPlayer().setSpectatorTarget(e.getRightClicked());
    }
    
    @EventHandler(priority = EventPriority.HIGHEST)
    public void onPlayerToggleFlight(final PlayerToggleFlightEvent e) {
        final GamePlayer gamePlayer = GamePlayer.get(e.getPlayer().getUniqueId());
        if (gamePlayer.isSpectator() && this.game.isStarted() && SpectatorSettings.get(gamePlayer).getOption(SpectatorSettings.Option.FLY)) {
            e.setCancelled(true);
            if (e.getPlayer().isOnGround()) {
                e.getPlayer().getLocation().setY(e.getPlayer().getLocation().getY() + 0.1);
            }
        }
    }
    
    @EventHandler(priority = EventPriority.HIGHEST)
    public void onPlayerToggleSneak(final PlayerToggleSneakEvent e) {
        final GamePlayer gamePlayer = GamePlayer.get(e.getPlayer().getUniqueId());
        if (gamePlayer.isSpectator() && this.game.isStarted() && SpectatorSettings.get(gamePlayer).getOption(SpectatorSettings.Option.FIRSTPERSON) && e.getPlayer().getGameMode() == GameMode.SPECTATOR) {
            gamePlayer.sendTitle("§e退出旁观模式", "", 0, 20, 0);
            e.getPlayer().setGameMode(GameMode.ADVENTURE);
            e.getPlayer().setAllowFlight(true);
            e.getPlayer().setFlying(true);
        }
    }
    @EventHandler(priority = EventPriority.LOW)
    public void onSpawnProtection(final EntityDamageByEntityEvent e) {
        if (CitizensAPI.getNPCRegistry().isNPC(e.getEntity())) {
            return;
        }
        if (e.isCancelled()) {
            return;
        }
        if (game.isDeathMatch()){
            return;
        }
        if (e.getEntity() instanceof Player && e.getDamager() instanceof Player) {
            final GamePlayer damager = GamePlayer.get(e.getDamager().getUniqueId());
            final GamePlayer player = GamePlayer.get(e.getEntity().getUniqueId());
            if (damager==null||player==null){
                return;
            }
            if (damager.getGameTeam()==null||player.getGameTeam()==null){
                return;
            }
            if (!game.isStarted()){
                return;
            }
            if (damager.isSpectator() || damager.getGameTeam().isInTeam(player)) {
                return;
            }
            if (damager.getPlayer().hasPotionEffect(PotionEffectType.INCREASE_DAMAGE)){
                return;
            }
            if (damager.getGameTeam().getSpawnLocation().distance(player.getPlayer().getLocation())<spawnProtection) {
                e.setDamage(e.getDamage()*1.75);
                player.sendMessage(ChatColor.RED+ChatColor.BOLD.toString()+"因为靠近他人出生点，你将受到额外伤害!");
            }
        }
    }
}
